package controller;

import mapper.MovieMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pojo.Movie;
import service.MovieService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
public class MovieController {

    @Autowired
    private MovieService movieService;

    @GetMapping("/List")
    public String list(Model model, HttpServletRequest req, HttpServletResponse resp) {
        int pageSize = 2;
        int pageZym = 0;
        int pageNo = 1;
        String pageNo1 = req.getParameter("pageNo");
        if (req.getParameter("pageNo") != null) {
            pageNo = Integer.parseInt(req.getParameter("pageNo"));
        }
            int count = movieService.Count();
            pageZym = (count % pageSize == 0) ? count / pageSize : count / pageSize + 1;

            req.getSession().setAttribute("pageNo", pageNo);
            req.getSession().setAttribute("count", count);
            req.getSession().setAttribute("pageZym", pageZym);
            List<Movie> movies = movieService.limit(pageNo, pageSize);
            req.getSession().setAttribute("list", movies);
            return "list";
    }

    @GetMapping("toAdd")
    public String toAdd(){
        return "add";
    }

    @PostMapping("add")
    public String Add(Movie movie){
        int add = movieService.add(movie);
        if (add>0){
            return "redirect:List";
        }
        return "add";
    }
    @PostMapping("/MovieAccountExists")
    @ResponseBody
    public String accountExists(@Param("movieName") String movieName){
        Integer result = movieService.selectMovieName(movieName);
        return result>0?"false":"true";
    }
}
